class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
         vector<vector<int>> re;
         int n=nums.size();
        for(int j=0;j<n;)
        {
            for(int i=j+1;i<n;)
            {
                long long t=(long long)target-nums[i]-nums[j];
                int l=i+1;int r=n-1;
                while(l<r)
                {
                    if(nums[l]+nums[r]<t)
                    {
                        l++;
                        while(nums[l]==nums[l-1]&&l<r) l++;
                    }
                    else if(nums[l]+nums[r]>t)
                    {
                        r--;
                        while(nums[r+1]==nums[r]&&l<r) r--;
                    }
                    else{
                        vector<int> s{nums[j],nums[l],nums[r],nums[i]};
                        re.push_back(s);
                        l++;
                        while(nums[l]==nums[l-1]&&l<r) l++;
                        r--;
                        while(nums[r+1]==nums[r]&&l<r) r--;
                    }
                }
                i++;
                while(i<=n-2&&nums[i]==nums[i-1]) i++;
            }
            j++;
            while(j<n-3&&nums[j]==nums[j-1]) j++;
        }
       return re;
    }
};